package com.kangye.exam.service.serviceimpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kangye.exam.bean.Grade;
import com.kangye.exam.bean.Itembank;
import com.kangye.exam.bean.Subject;
import com.kangye.exam.dao.GradeDao;
import com.kangye.exam.dao.ItembankDao;
import com.kangye.exam.dao.SubjectDao;
import com.kangye.exam.service.ItemBankService;
import com.kangye.exam.utils.ExcelImportUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;

/*
 * @author 海风
 * @Description 题库表的service层
 * @data 2021-3-11 10:38:48
 * @since 1.0.4
 * */
@Service(value = "itemBankService")
public class ItemBackServiceImpl implements ItemBankService {

    @Resource
    private ItembankDao itembankDao;

    @Resource
    private GradeDao gradeDao;

    @Resource
    private SubjectDao subjectDao;

    @Autowired
    private ExcelImportUtils excelImportUtils;

    /*
     * @Description 按条件 模糊查询 分页
     * @itembank 题目类 从前台获取的查询条件
     * @pageNum 当前页
     * @pageSize 每页条数
     * @Return 返回PageInfo对象  分页插件封装好的对象类型
     * */
    @Override
    public PageInfo<Itembank> find_limit(Itembank itembank, Integer pageNum, Integer pageSize) {
        //分页插件PageHelper类 设置 当前页 每页条数
        PageHelper.startPage(pageNum, pageSize);
        List<Itembank> itembankList = itembankDao.selectByParm(itembank);
        return new PageInfo(itembankList);

    }

    /*
     * @Description 通过id查找单条题目
     * @id 题目id
     * @typeId 类型id,根据数值判断返回的url(1=单选,2=多选,3=判断,4=简答,5=编程)
     * @Return 返回一个题目对象
     * */
    @Override
    public Itembank selectByPrimaryKey(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("itemid", id);
        return itembankDao.selectByPrimaryKey(map);
    }

    /*
     * @Description 插入一条题目数据
     * @itembank 题目类
     * @Return 受影响条数
     * */
    @Override
    @Transactional
    public Integer insert(Itembank itembank) {

        return itembankDao.insertSelective(itembank);
    }

    /*
     * @Description 修改一条题目数据
     * @itembank 题目类
     * @Return 受影响条数
     * */
    @Override
    @Transactional
    public Integer update(Itembank itembank) {
        return itembankDao.updateByPrimaryKeySelective(itembank);
    }

    /*
     * @Description 删除一条数据
     * @id 删除数据的id
     * @Return 受影响条数
     * */
    @Override
    public Integer delete(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("itemId", id);
        return itembankDao.deleteByPrimaryKey(map);
    }

    /*
     * @Description 创建文件
     * @fileName 文件名
     * @file 文件流
     *
     * */
    @Override
    public String batchImport(String fileName, MultipartFile file) {
        File uploadDir = null;
        try {
            uploadDir = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //创建一个目录 （它的路径名由当前 File 对象指定，包括任一必须的父路径。）
        if (!uploadDir.exists()) uploadDir.mkdirs();
        //新建一个文件
        File tempFile = new File("E:\\upload\\" + UUID.randomUUID() + ".xlsx");
        //初始化输入流
        InputStream is = null;
        try {
            //将上传的文件写入新建的文件中
            file.transferTo(tempFile);

            //根据新建的文件实例化输入流
            is = new FileInputStream(tempFile);

            //根据版本选择创建Workbook的方式
            Workbook wb = null;
            //根据文件名判断文件是2003版本还是2007版本
            if (excelImportUtils.isExcel2007(fileName)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }
            //根据excel里面的内容读取知识库信息
            return readExcelValue(wb, tempFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        return "文件类型错误!请重新下载模板";
    }

    /**
     * 解析Excel里面的数据
     *
     * @param wb
     * @param tempFile
     * @return
     */
    private String readExcelValue(Workbook wb, File tempFile) {
        List<Itembank> itembankList = new ArrayList<>();
        //错误信息接收器
        String errorMsg = "";
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        int totalRows = sheet.getPhysicalNumberOfRows();
        //循环Excel行数,从第二行开始。标题不入库
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                //跳过空行
                continue;
            }
            //循环Excel的列
            Itembank itembank = new Itembank();

            try {
                Grade grade = gradeDao.selectByName(row.getCell(0).toString());
                itembank.setGradeId(grade.getGradeId());

                Subject subject = subjectDao.selectByName(row.getCell(1).toString());
                itembank.setSubjectId(subject.getSubjectId());

                row.getCell(2).setCellType(CellType.STRING);
                itembank.setTypeId(Integer.parseInt(row.getCell(2).toString()));
                itembank.setContent(row.getCell(3).toString());
                itembank.setOptions(row.getCell(4).toString());
                itembank.setAnswer(row.getCell(5).toString());
                itembank.setAnalysis(row.getCell(6).toString());
                row.getCell(7).setCellType(CellType.STRING);
                itembank.setScore(Integer.parseInt(row.getCell(7).toString()));
                row.getCell(8).setCellType(CellType.STRING);
                itembank.setDifficulty(Integer.parseInt(row.getCell(8).toString()));
            } catch (NullPointerException e) {
                errorMsg = "第" + (r + 1) + "行数据出错!请修改后在上传";
                tempFile.delete();
                return errorMsg;
            }
            itembankList.add(itembank);
        }
        //删除上传的临时文件
        if (tempFile.exists()) {
            tempFile.delete();
        }
        for (Itembank i : itembankList) {
            insert(i);
        }
        errorMsg = "上传完成";
        return errorMsg;
    }
}
